package com.bangbang.controller;

import com.bangbang.configresult.Result;
import com.bangbang.configresult.ResultEnum;
import org.apache.shiro.SecurityUtils;
import org.apache.shiro.authc.UsernamePasswordToken;
import org.apache.shiro.subject.Subject;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.RestController;

import java.util.UUID;

@RestController
@RequestMapping("/loginController")
public class LoginController {

    @Autowired
    private RedisTemplate redisTemplate;

    @PostMapping
    public Result tologin(@RequestParam(required = true) String username, @RequestParam(required = true) String pwd){
//      获取subject

        Subject subject = SecurityUtils.getSubject();
//        分装token
//          调用  login 方法
        UsernamePasswordToken tokens = new UsernamePasswordToken(username,pwd);
        subject.login(tokens);
//        获取登录成功的用户
        String token = UUID.randomUUID().toString().replace("-", "");
//        将用户保存 redis
        redisTemplate.boundValueOps(token).set(tokens);

        return Result.buildResult(ResultEnum.SUCCESS).setResult(token);
    }
}
